﻿using System;
using System.Collections.Generic;
using System.Dynamic;

namespace cludg.Domain
{
	using Extensions;

	public class ExtendableEntity : DynamicObject
	{
		protected class ExtensionValue
		{
			public DomainExtension Extension { get; set; }
			public Type Type { get; set; }
			public object Value { get; set; }
		}

		protected readonly Dictionary<string, ExtensionValue> ExtensionValues = new Dictionary<string, ExtensionValue>();

		protected virtual void AddExtension(DomainExtension extension)
		{
			ExtensionValues[extension.PropertyName] = new ExtensionValue
														{
															Extension = extension,
															Type = extension.PropertyType,
															Value = extension.DefaultValue
														};
		}

		protected internal virtual void InitExtensions(IEnumerable<DomainExtension> extensions)
		{
			ExtensionValues.Clear();
			foreach (var extension in extensions)
			{
				AddExtension(extension);
			}
		}

		protected virtual bool HasExtensionValue(string name)
		{
			return ExtensionValues.ContainsKey(name);
		}

		protected virtual object GetExtensionValue(string name)
		{
			return ExtensionValues[name].Value;
		}

		protected virtual void SetExtensionValue(string name, object value)
		{
			if (!ExtensionValues[name].Type.IsAssignableFrom(value.GetType()))
				throw new ApplicationException("Значение не того типа.");

			ExtensionValues[name].Value = value;
		}
	}
}
